package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.ftp.FtpConfig;
import com.pactera.madp.cp.common.util.sync.SFTPUtils;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.FundSftpConfig;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.service.sync.SyncFundOutlineService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

@Slf4j
@Service
@AllArgsConstructor
public class SyncFundOutlineServiceImpl implements SyncFundOutlineService {

    private final SyncConfig syncConfig;
    private final FundSftpConfig fundSftpConfig;

    @Override
    public void addYesterdayToHis() {
        log.debug("基金概要信息：addYesterdayToHis");
        String fileDate = SyncStateContext.get().getFileDate();
        String syncDir = syncConfig.getFundOutlineNewPath();
        String bakFilePath = SyncUtils.buildFolderPath(syncConfig.getFundOutlineHisPath(), fileDate);
        boolean flag = SyncUtils.bakAndDelFile(new File(syncDir), bakFilePath);
        if (!flag) {
            log.debug("基金概要文件目录{}备份失败", syncDir);
        }
    }

    @Override
    public void deleteYesterday() {
        log.debug("基金概要信息：deleteYesterday");
    }

    @Override
    public void parse() {
        log.debug("FTP获取数据文件");
        // 下载文件目录
        FtpConfig ftpConfig = new FtpConfig();
        BeanUtil.copyProperties(fundSftpConfig, ftpConfig);
        log.debug("host:" + ftpConfig.getHost());
        log.debug("port:" + ftpConfig.getPort());
        log.debug("username:" + ftpConfig.getUser());
        log.debug("password:" + ftpConfig.getPassword());
        String ftpDir = syncConfig.getFundOutlineFtpDir();
        // 下载目录检测
        // 本地目标目录
        String destDir = SyncUtils.buildFolderPath(syncConfig.getFundOutlineNewPath(), "");;
        log.debug("destDir:" + destDir);
        boolean flag = SyncUtils.checkDir(destDir, true);
        if (!flag) {
            log.debug("基金概要文件下载目录{}不存在", destDir);
        }
        log.debug("sourcePath:" + ftpDir);
        log.debug("destDir:" + destDir);
//        flag = SFTPUtils.recursiveDownloadFolder(ftpConfig, ftpDir, destDir);
        flag = SFTPUtils.downloadBatchFile(ftpConfig, ftpDir, destDir);
        if (!flag) {
            log.debug("基金概要文件下载目录{}批量下载失败", ftpDir);
        }
    }

    @Override
    public void deleteHisOneDay() {
        log.debug("基金概要信息：deleteHisOneDay");
    }

    @Override
    public void syncBusiness() {
        log.debug("基金概要信息：syncBusiness");
        SyncStateContext.get().setFinalState(true);
    }

}